package encryption;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;

public class RSAGenerator {
	
	public static final String algorithm = "RSA";
	
	public static final String PRIVATE_KEY_FILE = "C:/RSAKeys/private.key";
	
	public static final String PUBLIC_KEY_FILE = "C:/RSAKeys/public.key";
	
	public static void generateKey() throws NoSuchAlgorithmException, IOException{
		
		KeyPairGenerator keyGen = KeyPairGenerator.getInstance(algorithm);
		keyGen.initialize(1024);
		
		KeyPair key = keyGen.generateKeyPair();
		
		File privateKeyFile = new File(PRIVATE_KEY_FILE);
		File publicKeyFile = new File(PUBLIC_KEY_FILE);
		
		if(privateKeyFile.getParentFile() != null){
			privateKeyFile.getParentFile().mkdirs();
		}
		privateKeyFile.createNewFile();
		
		if(publicKeyFile.getParentFile() != null){
			publicKeyFile.getParentFile().mkdirs();
		}
		publicKeyFile.createNewFile();
		
		ObjectOutputStream publicKeyOS = new ObjectOutputStream(new FileOutputStream(publicKeyFile));
		publicKeyOS.writeObject(key.getPublic());
		publicKeyOS.close();
		
		ObjectOutputStream privateKeyOS = new ObjectOutputStream(new FileOutputStream(privateKeyFile));
		privateKeyOS.writeObject(key.getPrivate());
		privateKeyOS.close();
		
	}
	
	public static boolean areKeysPresent(){
		
		File privateKey = new File(PRIVATE_KEY_FILE);
		File publicKey = new File(PUBLIC_KEY_FILE);
		
		if(privateKey.exists() && publicKey.exists()){
			return true;
		}
		return false;
	}
	
	public static void main(String[] args) {
		
		try {
			if(!areKeysPresent()){
				generateKey();
			}
		} 
		catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} 
		catch (IOException e) {
			e.printStackTrace();
		}
		
	}

}
